<template>
  <div class="common-body">
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回</el-button
      >
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/orderManagement' }"
          >订单管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          v-if="$route.query.type === 'sunyao'"
          :to="{
            path: '/orderManagement/approval/item-list'
          }"
          >订单审批</el-breadcrumb-item
        >
        <el-breadcrumb-item
          v-else
          :to="{
            path: '/orderManagement/orderManagement-List/close'
          }"
          >订单关闭</el-breadcrumb-item
        >
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb">查看 {{ basicInfoObj.orderName }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div v-if="isTrue" class="detail-box ccui-clearfix">
      <div class="detail-info">
        <div class="detail-info-el-Label">
          <el-label :type="approving" v-if="approvingStatus"></el-label>
        </div>
        <div class="detail-info-form-container">
          <!-- 基本信息项-->
          <el-tabs v-model="activeName" class="el-tabs__customize">
            <el-tab-pane label="基本信息" name="a">
              <el-group-title class="d_jump">
                <template slot="groupTitle">
                  <el-form
                    :model="form"
                    ref="formDateBUI"
                    label-width="160px"
                    class="ccui-form"
                  >
                    <el-col
                      v-for="(item, index) in basicInfo"
                      :span="item.colSpan || 12"
                      :key="index"
                    >
                      <!--                    <el-form-item :label="item.label + '：'">-->
                      <!--                      <div :title="basicInfoObj[item.label]" class="ellipsis">-->
                      <!--                        {{ basicInfoObj[item.value] }}-->
                      <!--                      </div>-->
                      <!--                    </el-form-item>-->
                      <el-form-item
                        :label="item.label + '：'"
                        class="remarkClass"
                        :title="basicInfoObj[item.value]"
                        >{{ basicInfoObj[item.value] }}
                      </el-form-item>
                    </el-col>
                  </el-form>
                </template>
              </el-group-title>
            </el-tab-pane>
            <el-tab-pane label="采购清单" name="b">
              <purchaseList ref="purchaseList"></purchaseList>
            </el-tab-pane>
            <el-tab-pane label="附件" name="c">
              <detailAttachment ref="attachment"></detailAttachment>
            </el-tab-pane>
            <el-tab-pane label="发货单" name="d" v-if="isShowInvoice">
              <invoice ref="materialList" v-show="isShowInvoice"></invoice>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <!--  右边审批状态  -->
      <approval-read-record
        :approvalRecordData="activities"
      ></approval-read-record>
      <!--  按钮  -->

      <!--  底部导航栏及签名导出  -->
      <bottomGuide
        busiType="101"
        exportMethod="get"
        methodGetPageType="exportOrder"
        :approvalStatus="this.approving"
        :curPageId="$route.params.id"
        :businessCode="businessCode"
        @handleBack="handleBack"
      >
        <template
          slot="start"
          v-if="
            this.approving === 'pending' ||
            this.approving === 'sendback' ||
            this.approving === 'withdrawn'
          "
        >
          <li>
            <el-button
              type="bottom"
              icon="icon-ccui-disagree"
              @click="handleClosed"
              >关闭</el-button
            >
          </li>
        </template>
      </bottomGuide>

      <el-dialog
        title="关闭原因"
        v-if="isDialogShow"
        :visible.sync="isDialogShow"
        width="600px"
      >
        <el-form :model="form" ref="Form" label-position="right">
          <el-form-item label="关闭原因：" prop="resource">
            <el-radio-group v-model="form.resource">
              <el-radio :label="1">录入错误</el-radio>
              <el-radio :label="2">缺货</el-radio>
              <el-radio :label="3">执行完毕</el-radio>
              <el-radio :label="4">逾期未交货</el-radio>
              <el-radio :label="5">验收完成</el-radio>
              <el-radio :label="6">其他</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="说明：">
            <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="form.textarea"
              maxlength="200"
              show-word-limit
              autosize
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            size="mini"
            type="default-mini"
            @click="isDialogShow = false"
            >取 消</el-button
          >
          <el-button
            size="mini"
            type="primary-font-mini"
            @click="handleCloseReasonConfirm"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import invoice from "../components/detail/invoice";
import detailAttachment from "../components/detail/attachment";
import purchaseList from "../../orderAccount/components/detail/purchaseList";
import { ishasAgentId, formatNumber } from "@/basa/utils";
import { getOrder } from "../api/index";
import { closeApproval } from "../../orderAccount/api";
import publicComponent from "@/basa/components/public";
export default {
  name: "detail-approving",
  ame: "add-item",
  // mixins: [btnSlide],
  components: {
    detailAttachment,
    purchaseList,
    // anchorTitle,
    approvalReadRecord: publicComponent.approvalRecord,
    invoice,
    bottomGuide: publicComponent.bottomGuide
    // anchorTitleUnDeliver
  },
  created() {},
  data() {
    return {
      isTrue: false,
      // downloadUrl: this.$addUrlPerFix(process.env.VUE_APP_BASE_URL),
      form: {
        textarea: "",
        resource: 1
      },
      businessCode: "",
      isDialogShow: false,
      isShowInvoice: true, // 是否展示发货单
      approving: "1", // 审批状态
      approvingStatus: true, // 审批状态展示
      approvingType: {
        0: "pending", //待审批
        1: "approving", // 审批中
        3: "approvaled", // 审批通过
        4: "sendback", // 已退回
        2: "withdrawn" // 已撤回
      },
      activities: [],
      focus: "formDateBUI",
      basicInfoObj: {},
      activeName: "a",
      basicInfo: [
        {
          label: "订单编号",
          value: "orderNo"
        },
        {
          label: "订单名称",
          value: "orderName"
        },
        {
          label: "填报单位",
          value: "reportInOrgName"
        },
        {
          label: "分类名称",
          value: "thirdCategoriesOfName"
        },
        {
          label: "供应商名称",
          value: "partyBName"
        },
        {
          label: "合同编号",
          value: "contractCode"
        },
        {
          label: "合同名称",
          value: "contractName"
        },
        {
          label: "供应商联系人",
          value: "contractPerson"
        },
        {
          label: "供应商联系人手机号",
          value: "contractPersonTel"
        },
        {
          label: "编制人",
          value: "compileUser"
        },
        {
          label: "订单发出时间",
          value: "orderDeliveryTime"
        },
        {
          label: "订单状态",
          value: "bizStatusName"
        },
        {
          label: "备注说明",
          value: "remark"
        },
        {
          label: "关闭原因",
          value: "closeReason"
        },
        {
          label: "关闭时间",
          value: "closeTime"
        },
        {
          label: "说明",
          value: "closeDescription"
        }
      ],
      tableData: []
    };
  },
  methods: {
    getGetOrder() {
      let obj = {
        id: this.$route.params.id
      };
      getOrder(obj).then(res => {
        this.basicInfoObj = res.data.data.ocOrderBasic;
        this.businessCode = this.basicInfoObj.orderNo;
        this.basicInfoObj.orderDeliveryTime = this.basicInfoObj
          .orderDeliveryTime
          ? this.basicInfoObj.orderDeliveryTime
          : "";
        if (
          this.basicInfoObj.closeTime !== undefined &&
          this.basicInfoObj.closeTime !== null
        ) {
          this.basicInfoObj.closeTime = this.basicInfoObj.closeTime.substring(
            0,
            10
          );
        }
        if (this.basicInfoObj.bizStatus === "55") {
          this.basicInfoObj.bizStatusName = "已关闭";
        } else if (
          this.basicInfoObj.bizStatus === "5" &&
          this.basicInfoObj.isReceive === "1" &&
          this.basicInfoObj.isShipments === "1"
        ) {
          this.basicInfoObj.bizStatusName = "已发货";
        } else if (
          this.basicInfoObj.bizStatus === "5" &&
          this.basicInfoObj.isReceive === "0" &&
          this.basicInfoObj.isShipments === "0"
        ) {
          this.basicInfoObj.bizStatusName = "待接收";
        } else if (
          this.basicInfoObj.bizStatus === "5" &&
          this.basicInfoObj.isReceive === "1" &&
          this.basicInfoObj.isShipments === "0"
        ) {
          this.basicInfoObj.bizStatusName = "已接收";
        } else if (this.basicInfoObj.bizStatus === "5") {
          this.basicInfoObj.bizStatusName = "审批通过";
        } else if (this.basicInfoObj.bizStatus === "53") {
          this.basicInfoObj.bizStatusName = "关闭中";
        } else if (this.basicInfoObj.bizStatus === "54") {
          this.basicInfoObj.bizStatusName = "关闭退回";
        } else if (this.basicInfoObj.bizStatus === "52") {
          this.basicInfoObj.bizStatusName = "已撤回";
        }
        this.$nextTick(() => {
          if (res.data.data.ocOrderBills.length > 0) {
            this.$refs.purchaseList.tableData = res.data.data.ocOrderBills;
            this.$refs.purchaseList.tableData.forEach(item => {
              item.onWayNum = item.shipmentsNum - item.acceptanceNum;
              item.currentNum = formatNumber(item.currentNum, 3);
              item.shipmentsNum = formatNumber(item.shipmentsNum, 3);
              item.acceptanceNum = formatNumber(item.acceptanceNum, 3);

              if (item.deliveryTime) {
                item.deliveryTime = item.deliveryTime.substring(0, 10);
              }
              item.listAddress =
                item.deliveryAreaName +
                item.provinceName +
                item.cityName +
                item.countyName +
                item.deliveryPoints;
            });
          }
          if (res.data.data.files != []) {
            res.data.data.files.forEach(item => {
              item.fileSize = Math.round(item.fileSize / 1024) + "kb";
              // item.createTime = item.createTime.substring(0, 10);
            });

            this.$refs.attachment.tableData = res.data.data.files;
          }
        });
        if (this.basicInfoObj.bizStatusName === "关闭退回") {
          this.form.resource =
            res.data.data.ocOrderBasic.closeReasonCode === ""
              ? 1
              : parseInt(res.data.data.ocOrderBasic.closeReasonCode);

          this.form.textarea = res.data.data.ocOrderBasic.closeDescription;
        }
        if (res.data.data.shipList.length > 0) {
          console.log(112);
          this.$refs.materialList.tableData = res.data.data.shipList;
          // this.$refs.materialList.tableData[0].buildDate = this.$refs.materialList.tableData[0].buildDate.substring(
          //   0,
          //   10
          // );
          this.$refs.materialList.tableData.forEach(item => {
            switch (item.shipStatus) {
              case 1:
                item.shipStatusName = "待提交";
                break;
              case 2:
                item.shipStatusName = "运输中";
                break;
              case 3:
                item.shipStatusName = "待验收";
                break;
              case 4:
                item.shipStatusName = "验收中";
                break;
              case 5:
                item.shipStatusName = "验收完成";
                break;
              case 6:
                item.shipStatusName = "已拒收";
                break;
            }
          });
        } else {
          this.isShowInvoice = false;
        }
        res.data.data.approveRecords.forEach(item => {
          if (item.operState === 0) {
            item.icon = "el-icon-time";
            item.color = "#F5A623";
          }
        });
        this.isTrue = true;

        this.activities = res.data.data.approveRecords;
        this.approving =
          this.approvingType[res.data.data.ocOrderBasic.approveStatus];
        this.approvingStatus = false;
        this.$nextTick(() => {
          this.approvingStatus = true;
          console.log(11111, this.activities);
        });
      });
    },
    // 关闭原因对话框确认
    handleCloseReasonConfirm() {
      // 调用提交接口
      let obj = {};
      (obj.ids = [parseInt(this.$route.params.id)]),
        (obj.closeReasonCode = this.form.resource);
      obj.closeDescription = this.form.textarea;
      obj.isShowPageLoading = true;
      switch (this.form.resource) {
        case 1:
          obj.closeReason = "录入错误";
          break;
        case 2:
          obj.closeReason = "缺货";
          break;
        case 3:
          obj.closeReason = "执行完毕";
          break;
        case 4:
          obj.closeReason = "逾期未交货";
          break;
        case 5:
          obj.closeReason = "验收完成";
          break;
        case 6:
          obj.closeReason = "其他";
          break;
      }
      console.log("obj", obj);
      closeApproval(obj)
        .then(res => {
          let { code, message } = res.data;
          if (code === "0") {
            this.$message.success(message);
          } else {
            this.$showErrorMessage(message);
          }
          // this.$message({
          //   type: "success",
          //   message: `提交成功。`,
          //   duration: 2000,
          //   ccuiCustom: true
          // });
          this.isDialogShow = false;
          this.handleBack();
        })
        .catch(e => {
          this.$showErrorMessage(e);
          // this.$message({
          //   type: "error",
          //   message: e,
          //   duration: 2000,
          //   ccuiCustom: true
          // });
        });
    },
    handleClosed() {
      this.isDialogShow = true;
    },
    handleBack() {
      this.$router.push(
        sessionStorage.getItem("fromPath") || "/orderManagement/close/un-closed"
      );
      // this.$router.push({ path: "/orderManagement/close/un-closed" });
    },
    tabChange(item, index) {
      this.focus = item[0];
      this.$refs[item[0]].$el.scrollIntoView({
        behavior: "smooth", // 平滑过渡
        block: "start" // 上边框与视窗顶部平齐。默认值
      });
    }
  },
  beforeRouteEnter(to, from, next) {
    console.log(to, "lookMe");
    console.log(from);
    !(to.fullPath === from.fullPath) &&
      sessionStorage.setItem("fromPath", from.fullPath);
    next();
  },
  // 更改列表缓存状态
  beforeRouteLeave(to, from, next) {
    if (this.submitFlag === true) {
      for (var key in this.$vnode.parent.parent.componentInstance.cache) {
        delete this.$vnode.parent.parent.componentInstance.cache[
          ishasAgentId(to.path, key)
        ];
      }
    }
    this.isTrue = false;
    next();
  },
  activated() {
    this.getGetOrder();
  }
};
</script>

<style lang="scss" scoped>
// .detail-info {
//   width: calc(100% - 438px);
//   min-height: calc(100vh - 260px);
//   float: left;
//   background: #fff;
//   position: relative;
//   padding: 14px 20px 0 20px;
//   margin: 15px 0 80px;
// }
/deep/.el-table td,
.el-table th {
  padding: 0 0;
}
.detail-info-el-Label {
  position: absolute;
  width: 107px;
  right: 33px;
  top: 31px;
  z-index: 1;
}
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  white-space: normal;
  word-break: break-all;
  word-wrap: break-word;
}
/deep/.el-radio-group {
  width: 100px;
  font-size: 0;
}
/deep/.el-radio {
  color: #4a4a4a;
  font-weight: 500;
  cursor: pointer;
  white-space: nowrap;
  outline: 0;
  margin-right: 30px;
  line-height: 2;
  padding-top: 4px;
  padding-left: 10px;
}
.remarkClass {
  /deep/ .el-form-item__content {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    white-space: normal;
    word-break: break-all;
    word-wrap: break-word !important;
  }
}
</style>
